package com.thunder.rebot.rebotclient.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.limedia.explorer.constant.Constant;
import com.limedia.explorer.entity.ClientView;
import com.limedia.explorer.enums.Enums;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.control.MySurfaceView;
import com.thunder.rebot.rebotclient.control.OnRockerListener;
import com.thunder.rebot.rebotclient.entity.Network;
import com.thunder.rebot.rebotclient.service.ServiceClient;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuechunan on 18-7-2.
 */

public class MajorActivity extends BaseActivity implements SurfaceHolder.Callback ,View.OnClickListener {

    private static final String TAG = "MajorActivity";
    @BindView(R.id.center_txt)
    public TextView centerTxt;
    @BindView(R.id.left_img)
    public ImageView leftImg;
    @BindView(R.id.right_txt)
    public TextView rightTxt;
    @BindView(R.id.btn2)
    public TextView connectBtn;
    @BindView(R.id.ll_controller)
    public LinearLayout controllView;
    @BindView(R.id.connect_state_txt)
    public TextView connectState;
//    @BindView(R.id.iv_dataview)
//    public ImageView mDataView;
    @BindView(R.id.surfaceView)
    public SurfaceView surfaceView;
    private int zl = 0;
    private SurfaceHolder surfaceHolder;

    private static final int MSG_DEVICE_RESOLVED = 1;
    private static final int MSG_DEVICE_REMOVED = 2;
    private static final int MSG_DEVICE_ADDED = 3;
//	private static final int MSG_TEST_STOP_LOADING = 4;

    private int deviceNo = 0;

    private ClientView mClient1 = null;;
    private int mCurClientID = 0;


    private Handler mHandler = null;
    private LocalBroadcastManager mLoaclBroadcastManager = null;
    private LocalReceiver mLocalReceiver = null;
    private Context mContext = null;

    private List<String> clientUrls = new ArrayList<String>();

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void onClick(View view) {

    }


    class myFingerEven implements OnRockerListener {
        byte[] value = new byte[1];

        public void onRocker(int which) {
            int value = -1;
            if (which == 0) {
                value = ClientUtils.stopA;
            } else {
                zl = 0x01 << (which - 1);
                switch (zl) {
                    case 0x01:
                        value = ClientUtils.stopA;//摇杆1
                        break;
                    case 0x02:
                        value = ClientUtils.stopB;//摇杆2
                        break;
                    case 0x04:
                        value = ClientUtils.stopC;//摇杆3
                        break;
                    case 0x08:
                        value = ClientUtils.stopD;//摇杆4
                        break;
                    case 0x10:
                        value = ClientUtils.stopE;//摇杆5
                        break;
                    case 0x20:
                        value = ClientUtils.stopF;//摇杆6
                        break;
                    case 0x40:
                        value = ClientUtils.stopG;//摇杆7
                        break;
                    case 0x80:
                        value = ClientUtils.stopH;//摇杆8
                        break;
                }
            }
            if (ClientUtils.connectFlag) {
                final int valueSend = value;
                new Thread("send") {
                    public void run() {
                        Network.SomeRequest request = new Network.SomeRequest();
                        request.type = valueSend;
                        LogUtil.d(TAG, "客户端发送的==" + request.type);
                        ServiceClient.client.sendTCP(request);
                    }
                }.start();
            } else {
                Toast.makeText(MajorActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
            }
        }

        public void onRocker(MySurfaceView mySurfaceView, int which) {
            // TODO Auto-generated method stub

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i(TAG, "onCreate");
        setContentView(R.layout.activity_major);
        ButterKnife.bind(this);
        centerTxt.setText(R.string.title_txt);
        rightTxt.setText(R.string.face_register_txt);

        this.mContext = this;
        this.mLocalReceiver = new LocalReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_SERVICE_RESOLVED);
        intentFilter.addAction(Constant.ACTION_SERVICE_REMOVED);
        intentFilter.addAction(Constant.ACTION_SERVICE_ADDED);
        this.mLoaclBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
        this.mLoaclBroadcastManager.registerReceiver(this.mLocalReceiver, intentFilter);

        this.initListener();
        this.initView1();
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtil.i(TAG, "onStart");
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.i(TAG, "onResume  start");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        LogUtil.i(TAG, "onPause  start");
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.i(TAG, "onStop  start");
    }

    private void initView() {
        MySurfaceView myView = new MySurfaceView(this);
        myView.setRockerListener(new myFingerEven());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(50, 30, 50, 30);
        controllView.addView(myView, lp);
    }

    @Override
    public void onDestroy() {
        Log.i("onDestroy()", "in");
        this.mLoaclBroadcastManager.unregisterReceiver(this.mLocalReceiver);
        this.mClient1.releasePlayer();
        //this.stopService(new Intent(getApplicationContext(), DeviceDiscoverService.class));
        Log.i("onDestroy()", "out");
        super.onDestroy();
    }

    private void initListener() {
        this.mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {

            @Override
            public boolean handleMessage(Message msg) {
                Bundle bundle = null;
                switch(msg.what) {
                    case MSG_DEVICE_RESOLVED:
                        bundle = msg.getData();
                        onDeviceResolved(bundle.getString("ip"));
                        break;
                    case MSG_DEVICE_REMOVED:
                        break;
                    case MSG_DEVICE_ADDED:
                        break;
//				case MSG_TEST_STOP_LOADING:
//					mClient1.stopLoading();
//					mClient3.stopLoading();
//					break;
                }
                return true;
            }
        });
    }

    private void initView1() {

        this.findViewById(R.id.preview_first).setOnClickListener(this);

        this.mClient1 = new ClientView();

        this.mClient1.setmSurfaceView((SurfaceView)this.findViewById(R.id.preview_first).findViewById(R.id.surfaceView));

        this.mClient1.setBackgroundView(this.findViewById(R.id.preview_first).findViewById(R.id.backgroundView));

        this.mClient1.setLoadingParam(
                (TextView)this.findViewById(R.id.preview_first).findViewById(R.id.loadingText),
                (ImageView)this.findViewById(R.id.preview_first).findViewById(R.id.loadingView),
                AnimationUtils.loadAnimation(this.mContext, R.anim.loading_animation));
        this.mClient1.setClientID("Camera 1");
        this.mClient1.setmClientNo(Enums.ClientNo.Client_ONE);
        this.mClient1.startLoading();
        SharedPreferences sharedPreferences = getSharedPreferences("ip", MODE_PRIVATE);
        String firstIpvalue = sharedPreferences.getString("FirstIpAddress", "");
        Log.e(TAG, "Address1"+firstIpvalue);
        this.onDeviceResolved(firstIpvalue);
    }

    protected void onDeviceResolved(String ip) {
        String url = Constant.PREFIX_RTSP_ADDR + ip + Constant.SUFFIX_RTSP_ADDR;
        Log.d(TAG, "onDeviceResolved: url is " + url);
        if(!this.clientUrls.contains(url)) {
            this.clientUrls.add(url);
            Log.d(TAG, "onDeviceResolved: add url--" + url);
            switch (++deviceNo) {
                case 1:
                    Log.d(TAG, "start client: " + deviceNo);
//				mClient1.setRtspUrl("rtsp://192.168.1.117:8899/live");
                    mClient1.setRtspUrl(url);
//				Toast.makeText(this.mContext, "Connect to client 1: " + url, Toast.LENGTH_SHORT).show();
                    if(mClient1.isSurfaceCreated()) {
                        mClient1.startPlayer();
                    } else {
                        mClient1.setDeviceAttached(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            switch (intent.getAction()) {
                case Constant.ACTION_SERVICE_RESOLVED:
                    String ip = intent.getStringExtra("ip");
                    Log.d(TAG, "ACTION_SERVICE_RESOLVED: ip is " + ip);
                    bundle.putString("ip", ip);
                    message.what = MSG_DEVICE_RESOLVED;
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                    break;
                case Constant.ACTION_SERVICE_REMOVED:
                    break;
                case Constant.ACTION_SERVICE_ADDED:
                    break;
                default:
                    break;
            }
        }
    }



    @OnClick({R.id.btn2, R.id.left_img, R.id.right_txt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                finish();
                //转一圈
//                byte[] value;
//                value = new byte[1];
//                value[0] = (byte) 'B';//摇杆1;
//                mChatService.write(value);
//                try {
//                    Thread.sleep(1950);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                value = new byte[1];
//                value[0] = (byte) 'Z';//摇杆1;
//                mChatService.write(value);
                break;
            case R.id.right_txt:
                Intent intentMain = new Intent(this, RegisterActivity.class);
                startActivity(intentMain);
                finish();
                break;
            case R.id.btn2:
//                Intent serverIntent = new Intent(this, DeviceListActivity.class);
//                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
                break;
        }
    }
}

